define(window.backboneCommon.getViewDefine("crowd.customInfo"), function ($,require,Collection,tpl) {
    var defaultsOptions={
        submitCallback:null
    };
    var pagePrivate = {
        getDefaults :function () {
            return defaultsOptions
        },
        getOptions : function (options) {
            options=$.ExtCommon.isCheckEmpty(options)?{}:options;
            return $.ExtCommon.initMergeJson(this.getDefaults(),options);
        }
    };
    var backboneView= Backbone.View.extend({
        events: {
            "click #btn_submitCustom": "saveSubmit"
        },
        initialize: function () {
            this.modelAttach={};
            this.modelAttach.baseData=this.model.get("modelBaseData");
            this.modelAttach.customer=this.model.get("modelCustomer");
            this.listenTo(this.modelAttach.baseData, 'bind:CrowdBag', this.bindBag);
            this.listenTo(this.modelAttach.customer, 'bind:AllList', this.bindCustomer);
            this.listenTo(this.model, 'bind:CustomInfo', this.bindInfo);
            this.listenTo(this.model, 'save:CustomInfo', this.saveInfoCallback);
            this.render();
        },
        render:function(){
            var templateHtml=_.template(tpl);
            this.$el.html(templateHtml());
            return this;
        },
        initMain:function(options){
            this.elementModel={
                modal:$('#modal_detailsCustom'),
                form:$('#form_detailsCustom')
            };
            this.extObject={};
            this.pageData={initPage:false};
            this.pageOptions=$.ExtCommon.initMergeJson(pagePrivate.getOptions(),options);
            this.elementModel.form.ExtParsley();
            this._initPagePower();
        },
        _initPagePower:function(){
            var self=this;
            $.ExtAssist.rolePower.operatePage("create|edit",["advertiserList"],function(json){
                self.pageData.powerInfo=json;
            });
        },
        initPage:function (id) {
            this.collection.getCustomInfo(id);
        },
        bindInfo:function () {
            var self=this;
            var result=this.model.get("dataCustomInfo");
            self.pageData.isAdd=result.isAdd;
            self.elementModel.modal.find(".modal-title").text($.ExtCommon.getStringConnect("{0}自定义人群",self.pageData.isAdd?"新建":"编辑"));
            self.extObject.formValue=self.elementModel.form.ExtFormValue({isRunBind:false,
                initCallback:function(dataJson) {
                    self.pageData.customInfo = dataJson;
                    if(!self.pageData.initPage) {
                        self.pageData.initPage = true;
                        self.collection.initAfterCustomInfo();
                        if(self.pageData.powerInfo["advertiserList"]){self.collection.getCustomer()}
                        self._initUpLoadFile();
                    }
                    if(self.extObject.customer){self.pageData.isAdd?self.extObject.customer.removeDisabled():self.extObject.customer.disabled()}
                    self._bindFileUrl(dataJson.fileData);
                    self._initPageElementShow();
                    self.elementModel.form.ExtParsley("reset");
                    self._showModal();
                }
            });
            self.extObject.formValue.cleanValue();
            self.extObject.formValue.bindValueData(result.res.data);
        },
        _initPageElementShow:function () {
            var self=this;
            self._checkExtComplete(function () {
                if(self.pageData.isAdd){
                    if(self.pageData.powerInfo["customer"]){self.extObject.customer.removeDisabled()}
                    self.extObject.bag.cleanDisabledAll();
                }else{
                    if(self.pageData.powerInfo["customer"]){self.extObject.customer.disabled()}
                    self.extObject.bag.disabledAll();
                }
                $("#panel_file,#file_text_remark").toggle(self.pageData.isAdd);
            })
        },
        _checkExtComplete:function (cb) {
            var self=this;
            var isCustomer=false;
            if(self.pageData.powerInfo["customer"]){
                if(self.extObject.customer){
                    isCustomer=true;
                }
            }else{
                isCustomer=true;
            }
            if(isCustomer && self.extObject.bag){
                cb()
            }else{
                setTimeout(function () {
                    self._checkExtComplete(cb)
                },50);
            }
        },
        bindCustomer:function () {
            var self=this;
            var res=this.modelAttach.customer.get("dataAllList");
            var list=$.ExtCommon.convertListByPara(res.data,{name:"nameExt"});
            self.extObject.customer= $("#ddl_customer").ExtSelect2({placeholder: "-请选择-",minimumResultsForSearch: 1,infoExt: {data: list,
                initCallback:function () {if(!self.pageData.isAdd){self.extObject.customer.disabled()}},
                changeCallback: function (value, element) {
                    self.elementModel.form.ExtParsley().validate(element)
                }
            }});
        },
        bindBag:function () {
            var res=this.modelAttach.baseData.get("dataCrowdBag");
            this.extObject.bag=$("#panel_custom_bag").ExtRadioCheckbox({type: "radio",attrName:"bagType",isInline:false,data: res.data});
        },
        _initUpLoadFile:function() {
            var self=this;
            var url= this.modelAttach.baseData.get("defUploadFile");
            $("#file_bag").ExtUploadFile({
                initShowType:"buttonFile",
                maxSize:100*1024,
                infoExt:{isImgType:false,fileType:"zip"},
                ajaxInfoCallback:{
                    url:url,
                    success:function(element,resData){
                        self.elementModel.form.ExtParsley().validate(element);
                        self._bindFileUrl(resData);
                    }
                }
            });
        },
        _bindFileUrl:function (json) {
            var el=$("#btn_file_url");
            if(!$.ExtCommon.isCheckEmpty(json)){
                var url=json["relativePath"];
                if(url){
                    var title=url.substr(url.lastIndexOf("/")+1);
                    title=title.substr(0,title.lastIndexOf("."));
                    el.attr("href",url).data({fileId:json["uploadId"],filePath:json["path"]}).text(title).parent().show();
                }
            }else{
                el.removeAttr("href").removeData(["fileId","filePath"]).parent().hide();
            }
        },
        _checkForm:function (data) {
            $.ExtNotify.destroy();
            var isCheck=true;
            if(this.pageData.isAdd){
                if($.ExtCommon.isCheckEmpty(data.filePath)) {
                    isCheck=false;
                    $.ExtNotify.error("请上传文件");
                }
                if($.ExtCommon.isCheckEmpty(data.bagType)) {
                    isCheck=false;
                    $.ExtNotify.error("请选择号码包类型");
                }
            }
            return this.elementModel.form.ExtParsley("validate") && isCheck;
        },
        saveSubmit:function () {
            var ajaxData = this.elementModel.form.ExtFormValue("getValues");
            var elementUrl=$("#btn_file_url");
            ajaxData.fileId=elementUrl.data("fileId");
            ajaxData.filePath=elementUrl.data("filePath");
            ajaxData.fileUrl=elementUrl.attr("href");
            if(this._checkForm(ajaxData)){
                var infoOriginal = this.elementModel.form.ExtFormValue("getOriginalData");
                if(infoOriginal.id){ajaxData.id=infoOriginal.id}
                this._hideModal();
                this.collection.saveCustomInfo(ajaxData);
            }
        },
        saveInfoCallback:function () {
            var result=this.model.get("dataSaveCustom");
            if (result.res.success) {
                $.ExtNotify.success("保存成功!");
                if(this.pageOptions.submitCallback){this.pageOptions.submitCallback(result.isAdd,result.req);}
            }else{
                this._showModal();
                $.ExtNotify.error(result.res.msg);
            }
        },
        _showModal:function(){
            this.elementModel.modal.modal("show");
            $.ExtAssist.modal.computeTop(this.elementModel.modal);
        },
        _hideModal: function () {
            this.elementModel.modal.modal("hide");
        }
    });
    var viewModel=function(options){
        this.collection= new Collection();
        this.model=this.collection.model;
        this.view=new backboneView({el:options.pElement,collection:this.collection,model:this.model});
        this.view.initMain(options);
    };
    viewModel.prototype={
        init:function (id) {
            this.view.initPage(id);
        }
    };
    return viewModel;
});